﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Word = Microsoft.Office.Interop.Word;
using System.Text;
using System.Linq.Expressions;
using System.IO;

public partial class Manage_StatAppraise : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region 绑定年、月、日
            for (int i = 2012; i <= 2007 + 10 || i <= DateTime.Now.Year + 2; i++)
            {
                Year1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Year2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 12; i++)
            {
                Month1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Month2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }
            for (int i = 1; i <= 31; i++)
            {
                Day1.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
                Day2.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
            }

            Year2.SelectedValue = Convert.ToString(DateTime.Now.Year);
            Month2.SelectedValue = Convert.ToString(DateTime.Now.Month);
            Day2.SelectedValue = Convert.ToString(DateTime.Now.Day);
            #endregion

            #region 加载教师信息
            CmsDataContext db = new CmsDataContext();
            var q = from aT in db.Teacher
                    select aT;

            XmlDocument doc = new XmlDocument();
            doc.Load(Toolkit.GetRealDataFilePath("Department.xml"));
            XmlElement root = doc.DocumentElement;

            //选择县区
            foreach (XmlNode node in root.SelectNodes("/Root/District"))
            {
                TreeNode tn1 = new TreeNode();
                string district = node.Attributes["name"].Value;
                tn1.Text = district;
                tn1.Value = district;
                tn1.NavigateUrl = "javascript:void(0)";

                Teachers.Nodes.Add(tn1);
                tn1.CollapseAll();


                //加载其单位
                foreach (XmlNode node2 in root.SelectNodes(string.Format("/Root/District[@name='{0}']//Depart", district)))
                {
                    TreeNode tn2 = new TreeNode();
                    string depart = node2.Attributes["name"].Value;

                    tn2.Value = depart;
                    tn2.Text = depart;
                    tn2.NavigateUrl = "javascript:void(0)";

                    tn1.ChildNodes.Add(tn2);
                    tn2.CollapseAll();

                    //加载其教师信息
                    foreach (Teacher t in q.Where(aT => aT.District == district && aT.Belong == depart))
                    {
                        TreeNode tn3 = new TreeNode();

                        tn3.Text = t.Name;
                        tn3.Value = "T:" + t.ID;
                        
                        tn3.NavigateUrl = "javascript:void(0)";

                        tn2.ChildNodes.Add(tn3);
                    }
                }
            }
            #endregion
        }
    }
    protected void Export_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        try
        {
            StringBuilder sb = new StringBuilder();
            #region 在树控件中查询所有教师的编号
            foreach (TreeNode n1 in Teachers.Nodes)
            {
                string val1 = n1.Value;
                if (n1.Checked && val1.StartsWith("T:"))
                {
                    sb.Append(" " + val1.Substring(2));
                }

                foreach (TreeNode n2 in n1.ChildNodes)
                {
                    string val2 = n2.Value;
                    if (n2.Checked && val2.StartsWith("T:"))
                    {
                        sb.Append(" " + val2.Substring(2));
                    }

                    foreach (TreeNode n3 in n2.ChildNodes)
                    {
                        string val3 = n3.Value;
                        if (n3.Checked && val3.StartsWith("T:"))
                        {
                            sb.Append(" " + val3.Substring(2));
                        }
                    }
                }
            }
            #endregion

            CmsDataContext db = new CmsDataContext();
            var q = from aT in db.Train
                    orderby aT.Teacher.Name, aT.Started descending
                    select aT;

            #region 查询条件
            Expression<Func<Train, bool>> lmbda = PredicateBuilder<Train>.CreatePredicate(new string[] { "TeacherID" }, sb.ToString().Trim(), "aT");
            var p = q.Where(lmbda);
            #endregion

            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatTeacherDetail)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            foreach (Train t in p)
            {
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = t.Teacher.Name;

                cell = row.Cells[3];
                cell.Range.Text = t.Belong;

                cell = row.Cells[4];
                cell.Range.Text = t.Teacher.Rank;

                cell = row.Cells[5];
                cell.Range.Text = string.Format("{0:yyyy年MM月dd日 HH:mm}", t.Started);

                cell = row.Cells[6];
                cell.Range.Text =t.Name;

                cell = row.Cells[7];
                cell.Range.Text = t.Course;

                cell = row.Cells[8];
                cell.Range.Text = Convert.ToString(t.JoinTrain.Count());

                cell = row.Cells[9];
                cell.Range.Text = t.Rank;

                //cell = row.Cells[10];
                //cell.Range.Text = t.Remark;
            }

            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
    protected void Export2_Click(object sender, EventArgs e)
    {
        DateTime st = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year1.SelectedValue, Month1.SelectedValue, Day1.SelectedValue));
        DateTime ed = DateTime.Parse(string.Format("{0}年{1}月{2}日", Year2.SelectedValue, Month2.SelectedValue, Day2.SelectedValue));

        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        try
        {
            StringBuilder sb = new StringBuilder();
            #region 在树控件中查询所有教师的编号
            foreach (TreeNode n1 in Teachers.Nodes)
            {
                string val1 = n1.Value;
                if (n1.Checked && val1.StartsWith("T:"))
                {
                    sb.Append(" " + val1.Substring(2));
                }

                foreach (TreeNode n2 in n1.ChildNodes)
                {
                    string val2 = n2.Value;
                    if (n2.Checked && val2.StartsWith("T:"))
                    {
                        sb.Append(" " + val2.Substring(2));
                    }

                    foreach (TreeNode n3 in n2.ChildNodes)
                    {
                        string val3 = n3.Value;
                        if (n3.Checked && val3.StartsWith("T:"))
                        {
                            sb.Append(" " + val3.Substring(2));
                        }
                    }
                }
            }
            #endregion

            CmsDataContext db = new CmsDataContext();
            var q = from aT in db.Teacher
                    select aT;

            #region 查询条件
            Expression<Func<Teacher, bool>> lmbda = PredicateBuilder<Teacher>.CreatePredicate(new string[] { "ID" }, sb.ToString().Trim(), "aT");
            q = q.Where(lmbda);
            #endregion

            var p = q.OrderBy(aT => aT.Name);

            string path = Toolkit.MappingPath(Toolkit.PathOfTemporary);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Toolkit.MappingPath(string.Format("{0}/{1}", Toolkit.PathOfReport, Toolkit.TemplateOfStatTeacherAll)), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["Time"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}", DateTime.Now);

            bm = doc.Bookmarks["Person"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["During"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日}-{1:yyyy年MM月dd日}", st, ed);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            foreach (Teacher t in p)
            {
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);

                cell = row.Cells[2];
                cell.Range.Text = t.Name;

                cell = row.Cells[3];
                cell.Range.Text = t.Belong;

                cell = row.Cells[4];
                cell.Range.Text = t.Rank;

                cell = row.Cells[5];
                cell.Range.Text = Convert.ToString(t.Train.Where(aT=>aT.Started.CompareTo(DateTime.Now)<=0).Count());

                cell = row.Cells[6];
                cell.Range.Text = Convert.ToString(t.Train.Where(aT => aT.Rank == "优").Count());

                cell = row.Cells[7];
                cell.Range.Text = Convert.ToString(t.Train.Where(aT => aT.Rank == "良").Count());

                cell = row.Cells[8];
                cell.Range.Text = Convert.ToString(t.Train.Where(aT => aT.Rank == "一般").Count());

                cell = row.Cells[9];
                cell.Range.Text = Convert.ToString(t.Train.Where(aT => aT.Rank == "差").Count());

                cell = row.Cells[10];
                cell.Range.Text = Convert.ToString(t.Train.Select(aT => aT.JoinTrain).Count());
            }

            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.StackTrace;
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
}